<template>
  <div>
    <van-nav-bar title="用户注册"
    left-text="返回"
    left-arrow
    @click-left="goBack"
    />
    <div class="register-panel">
      <van-field
        v-model="username"
        type="text"
        label="用户名"
        icon="clear"
        placeholder="请输入用户名"
        required
        @click-icon="username=''"
        :error-message="usernameErrorMsg"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :error-message="passwordErrorMsg"
      />
      <div class="register-button">
        <van-button type="primary" @click="registerAction" :loading="openLoading" size="large">马上注册</van-button>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import url from '@/serviceAPI.config.js'
  import {Toast} from 'vant'
  export default {
    data() {
      return {
        username: '',
        password: "",
        openLoading:false,//是否开启用户注册的loading状态
        usernameErrorMsg:'',//当用户名注册出现错误是返回的信息
        passwordErrorMsg:'',//当密码出现错误是返回的信息
      }
    },
    methods:{
      goBack(){
        // window.history.go(-1)
        this.$router.go(-1)
      },
      registerAction(){
        //如果前面为真，执行后面，如果前面为假，则不执行
        this.chenkForm() && this.axiosRegisterUser()
      },
      axiosRegisterUser(){
        this.openLoading = true
        // 前台向后端发送请求，进行注册 (29集)
        axios({
          url:url.registerUser,
          method:'post',
          data:{
            userName:this.username,
            password:this.password
          }
        }).then(res=>{
          console.log(res)
          if(res.data.code == 200){
            // Toast是vant提供的提示组件
            Toast.success(res.data.message)
            this.$router.push('/')
          }else{
            console.log(res.data.message)
            this.openLoading = false
            Toast.fail('注册失败')
          }
        }).catch(err=>{
          console.log(err)
          Toast.fail('注册失败')
          this.openLoading = false
        })
      },
      //****表单验证方法 */
      chenkForm(){
        let isOk = true
        if(this.username.length<5){
          this.usernameErrorMsg = '用户名不能少于5位'
          isOk = false
        }else{
          this.usernameErrorMsg = ''
        }
        if(this.password.length<6){
          this.passwordErrorMsg = '密码不能少于6位'
          isOk = false
        }else{
          this.passwordErrorMsg = ''
        }
        return isOk
      }

    },
  }
</script>

<style scoped>
.register-panel{
  width: 96%;
  border-radius: 5px;
  margin: auto;
  padding-bottom: 80px;
  padding-top: 10px;
}
.register-button{
  padding-top: 10px;
}
</style>